import {Injectable} from '@angular/core';
import {Http, Response} from '@angular/http';
import {Observable} from 'rxjs/Observable';
import {Headers, RequestOptions} from '@angular/http';
import 'rxjs/add/operator/toPromise';
import 'rxjs/add/operator/timeout';

import {RestEntity} from '../domain/RestEntity';
import {Constants} from "../domain/Constants";
import {StorageService} from "./storage-service";
import {User} from "../domain/User";
import {Router} from "@angular/router";

@Injectable()
export class HttpService {
    hostUrl: string = "http://desk.yuetingclub.com";
    TIME_OUT: number = 30000;

    constructor(private http: Http,
                public storageService: StorageService,private router: Router) {
        //this.local = new Storage(LocalStorage);
    }

    public httpPostLoginForm(url:string,param:string,username:string,password:string) {
        url = `${this.hostUrl}/${url}`;
        var headers = new Headers();
        headers.append('Content-Type', 'application/x-www-form-urlencoded');
        return this.http.post(url, param, {headers: headers}).timeout(this.TIME_OUT).toPromise()
            .then(res => res.json())
            .catch(err => {
                this.handleError(err);
            });
    }

    /**带身份验证的get请求 */
    public httpGetWithAuth(url: string): Promise<RestEntity> {
        url = `${this.hostUrl}/${url}`;
        var headers = new Headers();
        let token = this.getToken();
        if (token == null) {
            console.log('异常', 'Token获取错误');
            return;
        }
        headers.append(Constants.AUTHORIZATION, token);
        let options = new RequestOptions({headers: headers});

        return this.http.get(url, options).timeout(this.TIME_OUT).toPromise()
            .then(res => res.json() as RestEntity)
            .catch(err => {
                this.handleError(err);
            });
    }

    /**不需身份验证的get请求 */
    public httpGetNoAuth(url: string) {
        url = `${this.hostUrl}/${url}`;
        var header = new Headers();
        header.append('Content-Type', 'application/json');
        // if(token!=null)
        // header.append('X-Auth-Token', "4_e2ddade2c55047a0b6e13e1136bc7758");
        // headers.append("X-Auth-Token", "42423423423432");
        // let options = new RequestOptions({headers: headers,});
        return this.http.get(url, {headers:header}).timeout(this.TIME_OUT).toPromise()
            .then(res => res.json())
            .catch(err => {
                console.log('访问错误：' + err);
                this.handleError(err);
            });
    }

    /**不带身份验证的post请求 */
    public httpPostNoAuth(url: string, body: any): Promise<RestEntity> {
        url = `${this.hostUrl}/${url}`;
        var headers = new Headers();
        headers.append('Content-Type', 'application/json');
        let options = new RequestOptions({headers: headers});
        return this.http.post(url, body, options).timeout(this.TIME_OUT).toPromise()
            .then(res => res.json())
            .catch(err => {
                this.handleError(err);
            });
    }

    public httpPostWithAuth(url: string, body: any): Promise<RestEntity> {
        url = `${this.hostUrl}/${url}`;
        var headers = new Headers();
        let token = this.getToken();
        if (token == null) {
            console.log('异常', 'Token获取错误');
            return;
        }
        headers.append('Content-Type', 'application/json');
        headers.append(Constants.AUTHORIZATION, token);
        let options = new RequestOptions({headers: headers});
        return this.http.post(url, body, options).timeout(this.TIME_OUT).toPromise()
            .then(res => res.json())
            .catch(err => {
                console.log(err);
                this.handleError(err);
            });
    }

    private handleError(error: Response) {
        console.log("提示", error.toString());
        console.log("提示", error.json().status);
        if(error.json().status == "-1"){
            this.router.navigate(['/login']);
        }
        return Observable.throw(error.json().error || 'Server Error');
    }

    //
    // public loading():Loading{
    //    let loader = this.loadingCtrl.create({
    // 		spinner:"dots",
    // 		content:"loading...",
    // 		dismissOnPageChange:true, // 是否在切换页面之后关闭loading框
    // 		showBackdrop:false //是否显示遮罩层
    // 	});
    //     return loader;
    // }
    // public alert(msg:string,title?:string) {
    //     if(title==null) title='提示';
    //     this.dialogs.alert(msg,title);
    // }
    // public toast(msg:string,time?:number) {
    //     if(!time) time = 3000;
    //     let toast = this.toastCtrl.create({
    //         message: msg,
    //         duration: time
    //     });
    //     toast.present();
    // }
    /**当前登录用户 */
    public getCurrUser(): User {
        return this.storageService.read<User>(Constants.CURR_USER);
    }

    public getToken(): string {
        let user = this.getCurrUser();
        if (user == null) {
            console.log('Token错误，请登录后重试');
        }
        let token = user.userToken;

        return token;
    }

    public getRoleCode():string{
        let user = this.getCurrUser();
        if (user == null) {
            console.log('角色错误，请登录后重试');
        }
        let roleCode = user.authorities[0];
        return roleCode;
    }
}
